package com.yaolonga.itfc.manager.core.utils;

/**
 * @Author: yaolong
 * @CreateTime: 2024-11-15  15:18
 * @Description: 网络工具
 * @Version: 1.0
 */
public class NetUtil {


    // 根据ip地址+子网掩码计算网段
    public static String getNetSegment(String ip, String mask) {
        String[] ipSegments = ip.split("\\.");
        String[] maskSegments = mask.split("\\.");
        StringBuilder netSegment = new StringBuilder();
        for (int i = 0; i < ipSegments.length; i++) {
            int ipSegment = Integer.parseInt(ipSegments[i]);
            int maskSegment = Integer.parseInt(maskSegments[i]);
            int netSegmentSegment = ipSegment & maskSegment;
            netSegment.append(netSegmentSegment).append(".");
        }
        return netSegment.substring(0, netSegment.length() - 1);
    }

    // 获取掩码号
    public static int getMaskNum(String mask) {
        String[] maskSegments = mask.split("\\.");
        int maskNum = 0;
        for (String maskSegment : maskSegments) {
            int segmentNum = Integer.parseInt(maskSegment);
            maskNum += Integer.bitCount(segmentNum);
        }
        return maskNum;
    }


    public static void main(String[] args) {

        int maskNum = getMaskNum("255.255.0.0");
        System.out.println(maskNum);
    }
    public static String getMaskIp(int mask) {
        if (mask == 0){
            return "0.0.0.0";
        }
        StringBuilder maskIp = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            int mask1 = mask - i * 8;
            int mask2 = Math.min(mask1, 8);
            int mask3 = 0xff << (8 - mask2);
            maskIp.append((mask3 & 0xff)).append(".");
        }
        if (maskIp.toString().endsWith(".")) {
            return maskIp.substring(0, maskIp.length() - 1);
        }
        return maskIp.toString();
    }

}
